﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;


namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class ServiceCheckFailedMaintenancePlan : IssueTypeCheckBase
    {

        public ServiceCheckFailedMaintenancePlan()
        {
            IssueTypeId = 2015;
        }

        public override void Check()
        {
            try
            {
                // Database check AutoShrink is enabled 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);


                // Query for Databases with auto shrink enabled

                var Qry = from m in dc.SQLAgentJobDetails
                                     where m.LastRunStatus.ToLower() == "failed" 
                                     where m.Category.ToLower() == "database maintenance"
                                     select m;

                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                foreach (var job in Qry)
                {

                    //Create new Issue

                    Issue issue = new Issue();
                    issue.IssueType = issueType;
                    issue.TargetId = job.ServiceID;
                    issue.Description = issueType.Description.Replace("{MaintenancePlanJob}", job.JobName);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

    }
}
